/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.common;

import com.inspur.edp.lcm.metadata.common.configuration.WorkspaceHelper;
import io.iec.edp.caf.commons.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

@Slf4j
public class MavenUtils {
    public static final String pomFile = "pom.xml";

    public static final String tempFolder = "temp";

    public static final String resourcesDir = "src/main/resources";

    public static final String snapShot = "SNAPSHOT";

    private static String mavenHome;

    public static String getMavenHome() {
        if (!StringUtils.isEmpty(mavenHome)) {
            return mavenHome;
        }

        mavenHome = System.getenv("MAVEN_HOME");
        if (!StringUtils.isEmpty(mavenHome)) {
            return mavenHome;
        }
        mavenHome = System.getenv("M3_HOME");
        if (!StringUtils.isEmpty(mavenHome)) {
            return mavenHome;
        }
        mavenHome = System.getenv("M2_HOME");
        if (!StringUtils.isEmpty(mavenHome)) {
            return mavenHome;
        }
        String systemPath = System.getenv("Path");
        if (systemPath != null) {
            String[] paths = systemPath.split(File.pathSeparator);
            for (String path : paths) {
                if (path.contains("maven")) {
                    mavenHome = path.substring(0, path.length() - 4);
                }
            }
        }
        if (!StringUtils.isEmpty(mavenHome)) {
            return mavenHome;
        }
        throw new IllegalArgumentException("请配置maven环境变量！MAVEN_HOME=....");
    }

    public static String getSettingsPath() {
        String devRootPath = WorkspaceHelper.getInstance().getDevRootPath();
        if (StringUtils.isEmpty(devRootPath)) {
            log.info("无法获取工作空间");
            return null;
        }
        return FileServiceImp.combinePath(devRootPath, "maven", "config", "settings.xml");
    }

    public static String getSettingsPath(String mavenPath) {
        if (Utils.isNullOrEmpty(mavenPath)) {
            log.info("参数mavenPath为空");
            return null;
        }
        return FileServiceImp.combinePath(mavenPath, "config", "settings.xml");
    }
}
